/**
 * Zhznet.com Inc.
 * Copyright (c) 2004-2011 All Rights Reserved.
 */
package com.liwei.httpclient.demo;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import com.liwei.httpclient.util.CookieUtil;

/**
 * 用来演示登录表单的示例
 * @author Liwei
 * @version $Id: FormLoginDemo.java, v 0.1 2011-1-22 上午10:39:00 Liwei Exp $
 */
public class FormLoginDemo {

    static final String LOGON_SITE = "localhost";
    static final String SITE       = "/libCMS/j_spring_security_check";
    static final int    LOGON_PORT = 80;

    public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);

        // 模拟登录页面 login.jsp->main.jsp
        PostMethod post = new PostMethod(SITE);
        NameValuePair name = new NameValuePair("j_username", "admin");
        NameValuePair pass = new NameValuePair("j_password", "admin");
        post.setRequestBody(new NameValuePair[] { name, pass });
        int statuscode = client.executeMethod(post);

        if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
            || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER)
            || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            // 读取新的 URL 地址   
            Header header = post.getResponseHeader("location");
            if (header != null) {
                String newuri = header.getValue();
                if ((newuri == null) || (newuri.equals("")))
                    newuri = "/";
                GetMethod redirect = new GetMethod(newuri);
                client.executeMethod(redirect);
                System.out.println("Redirect:" + redirect.getStatusLine().toString());
                String response = new String(redirect.getResponseBodyAsString().getBytes("UTF-8"));

                //打印返回的信息
                System.out.println(response);

                // 查看 cookie 信息
                CookieUtil.getCookie(LOGON_SITE, SITE, LOGON_PORT, client);
                redirect.releaseConnection();
            } else
                System.out.println("Invalid redirect");

        }

        post.releaseConnection();

    }
}
